package cn.chinaunicom.fast.common.utils;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import org.springframework.beans.BeanUtils;

import com.google.common.collect.Maps;

import cn.chinaunicom.fast.common.constant.AuthConstant;
import cn.chinaunicom.fast.common.constant.Constants;
import cn.chinaunicom.fast.common.constant.SmartUser;
import cn.chinaunicom.fast.common.params.LoginUser4Redis;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
  *
  * @ProjectName:    common.core
  * @Package:        com.springboot.cloud.common.core.util
  * @ClassName:      UserContextHolder
  * @Description:    用户上下文(一次请求的上下文)
  * @Author:         wangjc
  * @CreateDate:     2020/3/18 0018 14:01
  * @UpdateUser:     更新者
  * @UpdateDate:     2020/3/18 0018 14:01
  * @UpdateRemark:   更新内容
  * @Version:        1.0
  */
@Setter
@Slf4j
public class UserContextHolder {
     /**
      * 线程安全的map
      */
    private ThreadLocal<Map<String, Object>> threadLocal;

    private UserContextHolder() {
        this.threadLocal = new ThreadLocal<>();
    }

    /**
     * 创建实例
     *
     * @return
     */
    public static UserContextHolder getInstance() {
        return SingletonHolder.instance;
    }

    /**
     * 静态内部类单例模式
     * 单例初使化
     */
    private static class SingletonHolder {
        private static final UserContextHolder instance = new UserContextHolder();
    }

    /**
     * 用户上下文中放入信息
     *
     * @param map
     */
    public void setContext(Map<String, Object> map) {
        threadLocal.set(map);
    }

    /**
     * 获取上下文中的信息
     *
     * @return
     */
    public Map<String, Object> getContext() {
        return threadLocal.get();
    }

    /**
     * 获取上下文中的用户名
     *
     * @return
     */
    public String getLoginName() {
        // FIXME 获取用户登录名
        return (String) Optional.ofNullable(getContext())
                .orElse(new HashMap<String,Object>(Constants.INT_YES_ONE))
                .get(AuthConstant.JWT_USERNAME);
    }

    /**
     * 获取当前用户的登录名
     * @param loginName
     */
    public void setLoginName(String loginName) {
        Optional.ofNullable(threadLocal.get()).orElse(new HashMap<>(Constants.INT_YES_ONE)).put(AuthConstant.JWT_USERNAME, loginName);
    }

     /**
      * 获取当前登录人信息
      * @return
      */
    public SmartUser getSmartUser() {
    	// 判断用户上下文是否存在
    	if (this.getContext() == null) {
    		log.error("用户上下文不存在");
    		this.setContext(Maps.newHashMap());
    	}
    	// 获取上下文中的smartUser
        LoginUser4Redis loginUser4Redis = (LoginUser4Redis) this.getContext().get(AuthConstant.JWT_SMART_USER);
        SmartUser smartUser = new SmartUser();
        BeanUtils.copyProperties(loginUser4Redis,smartUser);
        return smartUser;
    }

     /**
      * 获取租户编码
      *
      * @return
      */
    public String getTenantId(){
        return getSmartUser().getTenantId();
    }

    /**
     * 清空上下文
     */
    public void clear() {
        threadLocal.remove();
    }

}
